package cn.tedu.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;

//@Component
public class My01Filter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进入我的第一个过滤器");
        //响应相关处理的api
        //1.获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //2.拦截处理，准备一个响应信息，是一个json串
        String jsonData = "{\"state\":200,\"message\":\"你被拦截了\",\"data\":null}";
        //3.设置响应的相关的配置信息
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //4.将jsonData转成字节数组类型，并且设置字符集为utf-8
        byte[] bytes = jsonData.getBytes(StandardCharsets.UTF_8);
        //5.将字节数组封装成缓冲流
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        Mono<DataBuffer> dataBufferMono = Mono.fromSupplier(new Supplier<DataBuffer>() {
            @Override
            public DataBuffer get() {
                //将上面包装好的缓冲流返回
                return dataBuffer;
            }
        });
        return response.writeWith(dataBufferMono);//让响应正常返回
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
